package popple.display
{
	import flash.display.BitmapData;
	import flash.display.Stage;
	import flash.events.IEventDispatcher;
	import flash.geom.Matrix;
	import flash.geom.Matrix3D;
	import flash.geom.Vector3D;
	import flash.utils.Dictionary;
	
	import popple.display.DisplayObject;
	


	/**
	 *容器层,处理容器逻辑 
	 * @author Popple
	 * 
	 */	
	public class DisplayObjectContainer extends InteractiveObject
	{
		
		protected var mChildrenMap:Dictionary=new Dictionary;
		protected var mNumChildren:uint=0;
		protected var mMouseChildren:Boolean=true;
		protected var mChildrens:Vector.<DisplayObject>;
		
		private var _sort:Boolean;
		private var _sortKey:String="z";
		private var _sortFun:Function;
		public function DisplayObjectContainer()
		{
			super();
			mChildrens=new Vector.<DisplayObject>;
		}
		
		public function addChild(object:DisplayObject):DisplayObject
		{
			if(mChildrenMap[object]==null)
			{
				mChildrenMap[object]=object;
				
				object.parent=this;
				
				object.stage=this.stage;
				mNumChildren++;
			}
			updateChild();
			return object;
		}
		private function updateChild():void
		{
			mChildrens.length=0;
			var i:uint=0;
			for each(var child:DisplayObject in mChildrenMap)
			{
				mChildrens[i]=child;
				i++;
			}
		}
		/**
		 *按depth返回child集合; 
		 * @return 
		 * 
		 */		
		
		public function getChildren():Vector.<DisplayObject>
		{
			if(this._sort)
			{
				if(_sortFun!=null)
				mChildrens.sort(_sortFun);
			}
			
			return mChildrens;
		}
		public function sortBy(fun:Function):void
		{
			_sortFun=fun;;
		}
		public function set enableSort(value:Boolean):void
		{
			this._sort=value;
		}
		
		public function set mouseChildren(value:Boolean):void
		{
			mMouseChildren=value;
		}
		public function get mouseChildren():Boolean
		{
			return mMouseChildren;
		}
		
		
		public function getChildByName(name:String):DisplayObject
		{
			return mChildrenMap[name];
		}
		
		public function removeChild(obj:DisplayObject):void
		{
			var temp:DisplayObject;
			if(mChildrenMap[obj]!=null)
			{
				temp=mChildrenMap[obj] as DisplayObject;
				
				temp.parent=null;
				temp=null;
				mChildrenMap[obj]=null;
				delete mChildrenMap[obj];
				mNumChildren--;
			}
			updateChild();
		}
		
		public function getNumChildren():uint
		{
			return mNumChildren;
		}
	}
}